package com.klikmee.sms.core.base.handlers;

import com.klikmee.sms.core.base.util.DeliveryReports;
import com.klikmee.sms.core.base.util.States;
import com.klikmee.sms.core.model.IncomingMessage;
import com.klikmee.sms.core.model.OutgoingMessage;
import com.klikmee.sms.core.model.PaymentInvoice;

public class ChargedMessageDeliveryReportHandler extends AbstractDeliveryHandler {

	
	
	@Override
	public void handle( OutgoingMessage outgoingMessage ) {
		// get payment invoice
		PaymentInvoice paymentInvoice = outgoingMessage.getPaymentInvoiceList().iterator().next();

		// get incoming message id
		IncomingMessage incomingMessage = paymentInvoice.getIncomingMessage();

		Integer deliveryStatus = outgoingMessage.getDeliveryStatus();

		// switch delivery status trough all known statuses

		switch (deliveryStatus) {

			// first check if message is delivered
			case DeliveryReports.DELIVERED:

				// push im state
				switch (incomingMessage.getState()) {
					case States.IncommingMessage.BAD_SYNTAX_NOTIFICATION_SENT:
						incomingMessage.setState( States.IncommingMessage.BAD_SYNTAX_USER_NOTIFIED );
						break;

					case States.IncommingMessage.BAD_SEMANTIC_NOTIFICATION_SENT:
						incomingMessage.setState( States.IncommingMessage.BAD_SEMANTIC_USER_NOTIFIED );

					case States.IncommingMessage.SERVICE_NOT_AVAILABLE_NOTIFICATION_SENT:
						incomingMessage.setState( States.IncommingMessage.SERVICE_NOT_AVAILABLE_USER_NOTIFIED );

					default:
						break;
				}

				// push outgoing message
				outgoingMessage.setState( States.OutgoingMessage.DELIVERED );

				// push payment invoice
				paymentInvoice.setState( States.PaymentInvoice.CHARGED );
				
				break;

			//  check for failed delivery if user has insufficient funds				
			case DeliveryReports.Telenor.NOCREDIT:
				// TODO: check if this is the plase to send vip info message to user e.g. We are sorry but you don't have sufficient funds.
				outgoingMessage.setState( States.OutgoingMessage.UNDELIVERED );
				
				paymentInvoice.setState( States.PaymentInvoice.INSUFFICIENT_FUNDS );

				break;

			// all other statuses

			default:
				outgoingMessage.setState( States.OutgoingMessage.UNDELIVERED );
				paymentInvoice.setState( States.PaymentInvoice.UNDELIVERED_SERVICE );

		}

		// merge changes, OM & IM will be cascaded
		paymentInvoiceDAO.edit( paymentInvoice );

		// deliver status report to service
		boolean forwardSuccessfull = this.serviceMessageDeliverer.forwardDeliveryReport( outgoingMessage );
		if (forwardSuccessfull) {
			// if status forwarding was successful update states
			switch (outgoingMessage.getState()) {
				case States.OutgoingMessage.UNDELIVERED:
					outgoingMessage.setState( States.OutgoingMessage.UNDELIVERED_SERVICE_NOTIFIED );
					break;

				case States.OutgoingMessage.DELIVERED:
					outgoingMessage.setState( States.OutgoingMessage.DELIVERED_SERVICE_NOTIFIED );
					break;
				default:
					break;
			}
			outgoingMessageDAO.edit( outgoingMessage );
		}
	}
}
